package com.typhoon.spring_boot_demo1.dao;

import com.typhoon.spring_boot_demo1.bean.User;
import com.typhoon.spring_boot_demo1.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository("userDao")
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void create(String name,Integer sex,Integer age) {
        jdbcTemplate.update("insert into User(id,name,createTime,sex,age) values(null,?,now(),?,?)",name,sex,age);
    }

    public void deleteByName(String name) {
        jdbcTemplate.update("delete from User where name = ?",name);
    }

    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from User", Integer.class);
    }

    public void deleteAllUsers() {
        jdbcTemplate.update("delete from User");
    }

    public User queryByPK(Long id) {
        Map<String,Object> result = jdbcTemplate.queryForMap("select * from User where id = ? ",id);
        return BeanUtils.toBean(result, User.class);
    }

    public void updateByPk(Long id,String name,Integer age) {
        this.jdbcTemplate.update("update User set name=?,age=? where id=?",name,age,id);
    }

    public void deleteByPk(Long id) {
        jdbcTemplate.update("delete from User where id = ?",id);
    }
}
